<!--
 * @Descripttion: 
 * @version: 
 * @Author: -ViJia
 * @Date: 2022-02-10 16:26:27
 * @LastEditors: -ViJia
 * @LastEditTime: 2022-02-10 16:27:55
-->
<template>
  <div class="Main">
    <div class="MainTitle">商品详情</div>
    <div class="MianContent">
      <div class="formContent">
        <h2>商品基本信息</h2>
        <div>
          <a-form-model
            ref="ruleForm"
            :rules="rules"
            :model="form"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
          >
            <div class="formBox">
              <a-form-model-item label="商品分类">
                <!-- <a-cascader
                  :options="cateList"
                  v-model="form.cateId"
                  :fieldNames="fieldNames"
                  placeholder="选择商品分类"
                  @change="onChangeCate"
                /> -->
                <el-cascader
                  style="width: 100%;"
                  clearable
                  v-model="form.cateId"
                  :options="cateList"
                  :props="fieldNames"
                  @change="onChangeCate">
                </el-cascader>
              </a-form-model-item>
              <a-form-model-item label="商品名称" prop="title">
                <a-input v-model="form.title" placeholder="请输入商品名称" />
              </a-form-model-item>
              <a-form-model-item label="商品品牌">
                <a-select
                  show-search
                  v-model="form.brand_id"
                  allowClear
                  placeholder="输入品牌搜索"
                  :default-active-first-option="false"
                  :show-arrow="false"
                  :filter-option="false"
                  :not-found-content="null"
                  @search="handleSearch"
                >
                  <a-select-option v-for="d in ProductBrand" :key="d.id">
                    {{ d.title }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
              <a-form-model-item label="商品编码" prop="code">
                <a-input v-model="form.code" placeholder="请输入商品编码" />
              </a-form-model-item>
              <a-form-model-item label="商品简介" prop="synopsis">
                <a-textarea
                  placeholder="请输入商品简介，最长50字！"
                  :maxLength="50"
                  v-model="form.synopsis"
                  :rows="4"
                />
              </a-form-model-item>
              <a-form-model-item label="商品卖点" prop="sell_point">
                <a-textarea
                  placeholder="商品卖点，最长80字！"
                  v-model="form.sell_point"
                  :maxLength="80"
                  :rows="4"
                />
              </a-form-model-item>
            </div>
            <!-- <a-form-model-item label="药监类目" style="width: 60%">
              <a-radio-group name="radioGroup" v-model="form.drug_type">
                <a-radio :value="1"> 普通药品 </a-radio>
                <a-radio :value="2"> 保健品 </a-radio>
                <a-radio :value="3"> 医疗器械 </a-radio>
                <a-radio :value="4"> 中药类 </a-radio>
                <a-radio :value="5"> 其他商品 </a-radio>
              </a-radio-group>
            </a-form-model-item> -->
            <a-form-model-item
              label="商品类别"
              style="width: 50%"
              prop="category"
            >
              <a-checkbox-group v-model="form.category">
                <a-checkbox value="2">上新商品</a-checkbox>
                <a-checkbox value="3">热销商品</a-checkbox>
              </a-checkbox-group>
            </a-form-model-item>
			  <a-form-model-item label="秒杀商品" :labelCol="{ span: 2 }" :wrapperCol="{ span: 20 }">
			    <a-radio-group name="radioSeckill" v-model="form.activity_type">
			      <a-radio :value="0"> 否 </a-radio>
			      <a-radio :value="1"> 是</a-radio>
			    </a-radio-group>
				</a-form-model-item>
				<div v-if="form.activity_type==1">
					<a-form-model-item label="开始日期" :labelCol="{ span: 2 }" :wrapperCol="{ span: 20 }">
					  <a-date-picker
					    v-model="form.astime"
						:show-time="{ format: 'HH:mm' }"
						format="YYYY-MM-DD HH:mm"
					    :valueFormat="dateFormatTime"
					    @change="onChangeSeckillDate"
					  />
					</a-form-model-item>
					<a-form-model-item label="结束日期" :labelCol="{ span: 2 }" :wrapperCol="{ span: 20 }">
					  <a-date-picker
					    v-model="form.aetime"
						:show-time="{ format: 'HH:mm' }"
						format="YYYY-MM-DD HH:mm"
					    :valueFormat="dateFormatTime"
					    @change="onChangeSeckillEnd"
					  />
					</a-form-model-item>
					<a-form-model-item label="每天限购" prop="alimit" :labelCol="{ span: 2 }" :wrapperCol="{ span: 20 }">
					 <a-radio-group name="radioSeckill" v-model="form.is_daily">
					   <a-radio :value="0"> 否 </a-radio>
					   <a-radio :value="1"> 是</a-radio>
					 </a-radio-group>
					</a-form-model-item>
					<a-form-model-item label="限购数量" prop="alimit" :labelCol="{ span: 2 }" :wrapperCol="{ span: 20 }">
					  <a-input v-model="form.alimit" type="number" placeholder="请输入购买限制数量" style="width: 200px"/>
					</a-form-model-item>
				</div>
            <a-form-model-item
              label="计量规格"
              style="width: 50%"
              prop="meter_spec"
            >
              <a-input
                style="width: 100px"
                type="number"
                :min="0" 
                v-model="form.meter_spec"
                placeholder="请输入数量"
              ></a-input
              >（数量）
              <a-input
                v-model="form.medium_pack_spec"
                style="width: 130px; margin-left: 15px"
                placeholder="如：12盒"
              ></a-input
              >（中包装规格）
            </a-form-model-item>
            <a-form-model-item
              label="商品规格"
              style="width: 50%"
              prop="spec_unit"
            >
              <a-input
                style="width: 100px"
                v-model="form.spec_unit"
                placeholder="如：盒"
              ></a-input
              >（单位）
              <a-input
                v-model="form.spec_volume"
                style="width: 130px; margin-left: 15px"
                placeholder="如：250ml、24片"
              ></a-input
              >（容量规格）
            </a-form-model-item>
            
            <div class="formBox">
                <a-form-model-item label="批准文号" prop="approval_no">
                  <a-input v-model="form.approval_no" placeholder="必填" />
                </a-form-model-item>
                <a-form-model-item label="生产厂家" prop="manufacturer">
                  <a-input v-model="form.manufacturer" placeholder="必填" />
                </a-form-model-item>
                <a-form-model-item label="生产日期">
                  <a-date-picker
                    v-model="form.production_date"
                    :valueFormat="dateFormat"
                    @change="onChangeProductionDate"
                  />
                </a-form-model-item>
                <a-form-model-item label="有效日期">
                  <a-date-picker
                    v-model="form.expire_date"
                    :valueFormat="dateFormat"
                    @change="onChangeExpireDate"
                  />
                </a-form-model-item>
            </div>
            <div class="formBox">
                <a-form-model-item label="选择区域">
                  <a-select v-model="form.region_id" placeholder="请选择区域" allowClear style="width: 220px" @change="handleChangeArea">
                    <a-select-option :value="item.id" v-for="(item,index) in FirstAreaData" :key="index">{{item.name}}</a-select-option>
                  </a-select>
                </a-form-model-item>
                <a-form-model-item label="区域地点" v-if="form.region_id">
                  <a-select v-model="form.city_id" allowClear placeholder="请选择区域地点" style="width: 220px">
                    <a-select-option :value="item.id" v-for="(item,index) in SecondAreaData" :key="index">{{item.name}}</a-select-option>
                  </a-select>
                </a-form-model-item>
            </div>
            <div class="formBox">
                <a-form-model-item label="配送类型">
                  <!-- <a-checkbox-group v-model="form.delivery_type">
                    <a-checkbox value="1">平台配送</a-checkbox>
                    <a-checkbox value="2">到店自取</a-checkbox>
                  </a-checkbox-group> -->
                  <a-radio-group name="radioSeckill" v-model="form.delivery_type">
                    <a-radio :value="0">默认（配送+自取）</a-radio>
                    <a-radio :value="1">平台配送</a-radio>
                    <a-radio :value="2">到店自取</a-radio>
                  </a-radio-group>
                </a-form-model-item>
            </div>
            <div class="formBox">
                <a-form-model-item label="商品标签" prop="tag">
                  <a-input v-model="form.tag" type="text" placeholder="请输入商品标签（多个用 # 分割）" />
                </a-form-model-item>
            </div>
            <div class="formBox">
                <a-form-model-item label="购买限制数量" prop="buy_limit">
                  <a-input v-model="form.buy_limit" type="number" placeholder="请输入购买限制数量" />
                </a-form-model-item>
            </div>

            <div class="skuBox">
              <a-form-model-item label="售价" prop="sale_price">
                <a-input
                  v-model="form.sale_price"
                  type="number"
                  @input="changeSalePrice"
                  placeholder="请输入商品售价"
                />
              </a-form-model-item>
              <a-form-model-item label="原价" prop="primary_price">
                <a-input
                  v-model="form.primary_price"
                  type="number"
                  @input="changePrimaryPrice"
                  placeholder="请输入商品原价"
                />
              </a-form-model-item>
              <a-form-model-item label="成本价" prop="cost_price">
                <a-input
                  v-model="form.cost_price"
                  type="number"
                  @input="changeCostPrice"
                  placeholder="请输入商品成本价"
                />
              </a-form-model-item>
              <a-form-model-item label="库存" prop="num">
                <a-input
                  v-model="form.num"
                  type="number"
                  @input="changeNum"
                  placeholder="请输入商品库存"
                />
              </a-form-model-item>
              <a-form-model-item label="比例" prop="rate">
                <a-input
                  v-model="form.rate"
                  type="number"
                  @input="changeRate"
                  @blur="rulesRate"
                  placeholder="请输入商品比例（1-100%）"
                />
              </a-form-model-item>
              <!-- <a-form-model-item label="比例价">
                <a-input v-model="form.rate_price" type="number" disabled placeholder="药品比例价" />
              </a-form-model-item> -->

              <a-form-model-item label="分佣比例" prop="commission_rate">
                <a-input v-model="form.commission_rate" type="number" placeholder="请输入分佣比例" />
              </a-form-model-item>
            </div>
            <div>
              <a-form-model-item label="商品规格" :labelCol="{ span: 2 }" :wrapperCol="{ span: 20 }">
                <a-radio-group name="radioGroup" v-model="form.spec_type">
                  <a-radio :value="1"> 单规格 </a-radio>
                  <a-radio :value="2"> 多规格 </a-radio>
                </a-radio-group>
                <div class="skuTable" v-if="form.spec_type == 2">
                  <div class="skuInputBox">
                    <div class="skuInput flex align-center">
                      <a-input placeholder="请输入规格项" allowClear v-model="skuItem"></a-input>
                      <a-button icon="plus" type="primary" @click="addSkuItem">添加规格</a-button>
                    </div>
                    <div class="flex align-start" style="margin-top:15px;" v-for="(item,index) in skuData" :key="index">
                      <div class="flex align-center" style="flex-shrink:0;">{{item.skuItem}}<a-button icon="close" style="margin-left:10px;" @click="delSkuItem(index)"></a-button><a-input allowClear placeholder="请输入规格值" v-model="item.skuChild" style="width: 130px;"></a-input><a-button type="primary" @click="addSkuChild(item,index)">添加</a-button></div>
                      <div class="skuChild">
                        <div class="skuChildItem" v-for="(items,indexs) in item.child" :key="indexs">{{items.skuChild}}<a-icon type="close-circle" style="margin-left:10px;" @click="delSkuChild(index,indexs)" /></div>
                      </div>
                    </div>
                  </div>
                  <a-button icon="redo" type="primary" @click="creatSkuTable">刷新生成</a-button>
                  <div class="tableBox" v-if="skuTableData.length">
                      <!-- <a-table size="small" :columns="innerColumns" :data-source="skuTableData" :bordered="false" :pagination="false">
                          <div :slot="'sku'+indexs" slot-scope="row,index" v-for="(item,indexs) in skuData" :key="indexs">
                            {{index[indexs].value}}
                          </div>
                          <div slot="image" slot-scope="row,index">
                            <a-input style="width: 120px;" v-model="index[index.length-4].value"></a-input>
                          </div>
                          <div slot="num" slot-scope="row,index">
                            <a-input style="width: 120px;" v-model="index[index.length-3].value"></a-input>
                          </div>
                          <div slot="price" slot-scope="row,index">
                            <a-input style="width: 120px;" v-model="index[index.length-2].value"></a-input>
                          </div>
                          <div slot="primcost" slot-scope="row,index">
                            <a-input style="width: 120px;" v-model="index[index.length-1].value"></a-input>
                          </div>
                      </a-table> -->
                      <table>
                        <thead>
                          <tr>
                            <th style="text-align:center;" v-for="(item, index) in innerColumns"
                              :key="index">{{item}}</th>
                          </tr>
                        </thead>
                        <tbody>
                          <tr v-for="(item,index) in skuTableData" :key="index">
                            <td v-for="(item2,index2) in item" :class="item2.type=='规格'?'type':''"
                              :key="index2">
                              <div v-if="item2.type=='规格'">{{item2.value}}</div>
                              <div v-if="item2.type=='规格图'" class="spec_file">
                                <i class="el-icon-upload2" v-if="!item2.path"></i>
                                <input type="file" v-if="!item2.path"
                                  @change="handerFiles($event,index,index2)" />
                                <img :src="item2.path" alt="">
                              </div>
                              <a-input v-if="item2.type=='库存'" :min="0" type="number" v-model="item2.value"
                                style="width:110px" />
                              <a-input v-if="item2.type=='售价'" :min="0" type="number" v-model="item2.value"
                                style="width:110px" />
                              <a-input v-if="item2.type=='原价'" :min="0" type="number" v-model="item2.value"
                                style="width:110px" />
                              <a-input v-if="item2.type=='成本价'" :min="0" type="number" v-model="item2.value"
                                style="width:110px" />
                            </td>
                          </tr>
                        </tbody>
                      </table>
                  </div>
                </div>
              </a-form-model-item>
            </div>

            <!-- 药品图片 -->
            <div class="goodsImgBox">
              <h2>商品图片</h2>
              <div style="display: flex">
                <a-form-model-item
                  label="封面图片"
                  style="width: 45%"
                  prop="logo"
                >
                  <UploadImage v-model="logo" :multiple="false" :maxNum="1"></UploadImage>
                </a-form-model-item>
                <a-form-model-item label="商品图片" prop="image">
                  <UploadImage v-model="image" :maxNum="6"></UploadImage>
                </a-form-model-item>
              </div>
            </div>
            <!-- 药品图片 -->
            <div class="goodsImgBox">
              <h2>商品视频</h2>
              <div style="display: flex">
                <a-form-model-item
                  label="商品视频"
                  style="width: 45%"
                  prop="video"
                >
                  <UploadImage Accept="video/*" v-model="video" :maxNum="1"></UploadImage>
                </a-form-model-item>
              </div>
            </div>

            <!-- 产品描述 -->
            <div class="goodsImgBox">
              <h2>产品描述</h2>
              <a-form-model-item
                label="产品描述"
                :wrapperCol="{ span: 24 }"
                style="width: 50%"
              >
                <div style="width: 100%; height: 600px">
                  <editor-bar
                    v-model="form.desc"
                    :value="form.desc"
                    :isClear="false"
                  ></editor-bar>
                </div>
              </a-form-model-item>
            </div>

            <!-- 包装清单 -->
            <div>
              <h2>包装清单</h2>
              <a-form-model-item
                label="包装清单"
                :wrapperCol="{ span: 24 }"
                style="width: 50%"
              >
                <a-textarea
                  v-model="form.pack_list"
                  placeholder="包装清单"
                  :rows="5"
                />
              </a-form-model-item>
            </div>

            <!-- 售后服务 -->
            <div>
              <h2>售后服务</h2>
              <a-form-model-item
                label="售后服务"
                :wrapperCol="{ span: 24 }"
                style="width: 50%"
              >
                <a-textarea
                  v-model="form.after_service"
                  placeholder="售后服务"
                  :rows="5"
                />
              </a-form-model-item>
            </div>

            <!-- 智能标签 -->
            <div>
              <h2>智能标签</h2>
              <a-form-model-item
                label="智能标签"
                :wrapperCol="{ span: 24 }"
                style="width: 50%"
              >
                <a-textarea
                  v-model="form.smart_tag"
                  placeholder="在此描述..."
                  :rows="5"
                />
                <div>
                  添加智能标签，让用户更容易搜到这个商品（每一行添加一种标签）如:
                  <br />1、抖音热销零食<br />2、网红零食
                </div>
              </a-form-model-item>
            </div>
          </a-form-model>
        </div>
        <div class="btnBox">
          <el-button type="primary" @click="submitPush">提交申请</el-button>
          <el-button type="info">取消并删除内容</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue';
import { ACCESS_TOKEN, USER_DATA } from '@/store/mutation-types';
import { mapGetters, mapState, mapActions } from "vuex";
import { showErrors, showError, showSuccess } from "@/utils/showMsg";
import Pagination from "@/components/common/pagination.vue";
import EditorBar from "@/components/common/wangEnduit/wangEnduit";
import UploadImage from "@/components/common/Upload";
import axios from 'axios';
import env from '@/config/env';
import {
  GetConfigList,
  GetProductCate,
  GetProductBrandList,
  yxnShopGoodsAdd,
  yxnShopGoodsView,
  yxnShopGoodsEdit,
  upLoadFile,
  GetSpecAreaList,
} from "@/api/api.js";

export default {
  name: "list",
  components: {
    Pagination,
    UploadImage,
    EditorBar,
  },
  data() {
    return {
      rules: {
        title: [
          { required: true, message: "请输入商品名称!", trigger: "blur" },
        ],
        // code: [{ required: true, message: "请输入商品编码!", trigger: "blur" }],
        // synopsis: [
        //   { required: true, message: "请输入商品简介!", trigger: "blur" },
        // ],
        // sell_point: [
        //   { required: true, message: "请输入商品卖点!", trigger: "blur" },
        // ],
        // spec_unit: [
        //   { required: true, message: "请输入商品规格!", trigger: "blur" },
        // ],

        sale_price: [
          { required: true, message: "请输入售价!", trigger: "blur" },
        ],
        primary_price: [
          { required: true, message: "请输入原价!", trigger: "blur" },
        ],
        cost_price: [
          { required: true, message: "请输入成本价!", trigger: "blur" },
        ],
        num: [{ required: true, message: "请输入库存!", trigger: "blur" }],
        rate: [{ required: true, message: "请输入比例!", trigger: "blur" }],
        // region_id: [{ required: true, message: "请选择区域!", trigger: "blur" }],
        // city_id: [{ required: true, message: "请选择区域地点!", trigger: "blur" }],

        // meter_spec: [
        //   { required: true, message: "请输入计量规格!", trigger: "blur" },
        // ],
        commission_rate: [
          { required: true, message: "请输入分佣比例（1-100%）!", trigger: "blur",  pattern: new RegExp(/^([1-9][0-9]{0,1}|100)$/), },
        ],
        },
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      form: {
        cateId: undefined, //分类id
        title: "", //商品名
        brand_id: "", //药品品牌
        code: "", //编码
        synopsis: "", //简介
        sell_point: "", //药品卖点
        drug_type: 5, //药监类目(1普通药品,2保健品,3医疗器械,4中药类)，5其他商品
        meter_spec: "", //计量规格
        medium_pack_spec: "", //中包装规格
        spec_unit: "", //药品规格（单位）
        spec_volume: "", //药品规格（容量）

        approval_no: "", //批准文号
        manufacturer: "", //生产厂家

        // spec:'',//产品规格
        desc: "", //产品描述
        pack_list: "", //包装清单
        after_service: "", //售后服务
        smart_tag: "", //智能标签

        sale_price: "", //售价
        primary_price: "", //原价
        cost_price: "", //成本价
        rate_price: "", //比例价
        num: "", //库存
        rate: "", //比例
        
        production_date: null, //生产日期
        expire_date: null, //有效日期
        category: [], //类别(1高毛,2热销)
        activity_type:0, //1秒杀
        spec_type:1, //1单规格， 2多规格
        astime:'',//秒杀开始时间
        aetime:'',//秒杀结束时间
        alimit:'',//限购数量
        is_daily:0,//是否每天限购
        commission_rate:'', //分佣比例

        region_id:undefined, //区域id
        city_id:undefined, //区域地点id

        buy_limit:'', //限制购买数量

        delivery_type:0, //配送类型(1平台配送,2到店自取)
        tag:'', //商品标签
      },

      dateFormat: "YYYY-MM-DD",
	  dateFormatTime:"YYYY-MM-DD HH:mm",
      cateList: [],
      fieldNames: {
        label: "title",
        value: "id",
        children: "sub",
      },
      ProductBrand: "", //品牌数据
      logo: [], //商品图标
      image: [], //商品图片

      video:[], //商品视频

      goodsId: null, //商品id

      skuItem:'', //输入的规格项
      skuData:[], //每一组规格数据
      innerColumns:[],
      skuTableData:[], //生成的规格表格数据

      FirstAreaData:[], //区域数据
      SecondAreaData:[], //二级区域地点数据

      
    };
  },
  created() {},
  mounted() {
    const that = this;
    that.goodsId = that.$route.query.id;
    that.GetCateList();
    that.GetTBusinessList();
    that.handleSearch();
    // that.GetListFirst()
    if (that.goodsId) {
      that.GetGoodsDetails();
    }
  },
  methods: {

    // 获取上级区域列表
    async GetListFirst() {
      const that = this;
      let params = {
        page: 1,
        pagesize: 50,
        pid: 0
      };
      let res = await GetSpecAreaList(params);
      if (res.data.code == 1) {
        let data = res.data.data;
        that.FirstAreaData = data.regions;
        that.GetListSecond()
      } else {
        showError(res.data.msg);
      }
    },
    // 获取二级区域列表
    async GetListSecond() {
      const that = this;
      let params = {
        page: 1,
        pagesize: 100,
        pid: that.form.region_id
      };
      let res = await GetSpecAreaList(params);
      if (res.data.code == 1) {
        let data = res.data.data;
        that.SecondAreaData = data.regions;
      } else {
        showError(res.data.msg);
      }
    },

    // 选择一级区域
    handleChangeArea(){
      const that = this;
      that.form.city_id = undefined;
      that.GetListSecond()
    },

    // 获取商品详情
    async GetGoodsDetails() {
      const that = this;
      let res = await yxnShopGoodsView({ id: that.goodsId });
      if (res.data.code == 1) {
        let data = res.data.data;
        that.form = { ...data };
        that.form.astime=that.formatData(data.astime);
        that.form.aetime=that.formatData(data.aetime);

        // 分类
        // that.form.cateId = data.cate_id ? [data.cate_pid, data.cate_id] : [];
        // if(data.cate_pid){
        //   if(data.cate_id){
        //     that.form.cateId = [data.cate_pid, data.cate_id]
        //   }else{
        //     that.form.cateId = [data.cate_pid]
        //   }
        // }else{
        //   that.form.cateId = []
        // }
        
        if (data.cate_pid && data.cate_id){
          that.form.cateId = [data.cate_pid, data.cate_id]
        }else if (data.cate_pid && !data.cate_id){
          that.form.cateId = [data.cate_pid]
        }else if(!data.cate_pid && !data.cate_id) {
          that.form.cateId = []
        }

        
        that.form.region_id = data.region_id?data.region_id:undefined;
        that.form.city_id = data.city_id?data.city_id:undefined;
        // that.form.delivery_type = data.delivery_type?data.delivery_type:undefined;
        if(data.spec_type == 1){ //单规格
          that.form.sale_price = data.sku_list[0].sale_price;
          that.form.primary_price = data.sku_list[0].primary_price;
          that.form.cost_price = data.sku_list[0].cost_price;
          that.form.num = data.sku_list[0].num;
        }else{
          that.form.sale_price = data.sale_price;
          that.form.primary_price = data.primary_price;
          that.form.cost_price = data.cost_price;
          that.form.num = data.stock_num;

          // 每一组规格数据
          that.skuData = JSON.parse(data.specs)
          console.log(that.skuData);
          that.skuTableData = JSON.parse(data.lists)
          // 把规格id 赋值给老表格数据
          data.sku_list.map((item,index)=>{
            that.skuTableData.map((items,indexs)=>{
              if(index == indexs){
                items.map(itemss=>{
                  itemss.id = item.id;
                  if(itemss.type == '库存'){
                    itemss.value = item.num
                  }
                })
              }
            })
          })
          console.log(that.skuTableData);

          that.creatHeader()

        }
        that.form.category = data.category
          ? data.category.split(",")
          : [];

        if (data.logo) {
          //logo
          let imgArr = data.logo.split(",");
          let fileArr = [];
          imgArr.map((item) => {
            fileArr.push({ url: item });
          });
          that.logo = fileArr;
        }

        if (data.image) {
          //商品图片
          let imgArr = data.image.split(",");
          let fileArr = [];
          imgArr.map((item) => {
            fileArr.push({ url: item });
          });
          that.image = fileArr;
        }

        if (data.video) {
          //商品图片
          let videoArr = data.video.split(",");
          let fileArr = [];
          videoArr.map((item) => {
            fileArr.push({ url: item });
          });
          that.video = fileArr;
        }
      }
      that.form = JSON.parse(JSON.stringify(that.form))
      console.log(that.form,'form');
      console.log(that.form.cateId);
    },

    // 验证比例输入 计算比例价
    rulesRate() {
      const that = this;
      let reg = new RegExp("^([1-9]|[1-9]\\d|100)$");
      if (!reg.test(that.form.rate * 1)) {
        showError("请输入1-100的正整数！");
        that.form.rate = "";
      }
      // if(that.form.sale_price){
      //   that.form.rate_price = ((that.form.rate*1)/100)*(that.form.sale_price*1) + that.form.sale_price*1
      // }
    },

    // 验证输入
    changeSalePrice() {
      const that = this;
      let reg = /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/;
      if (!reg.test(that.form.sale_price)) {
        that.form.sale_price = "";
      }
    },
    // 验证输入
    changePrimaryPrice() {
      const that = this;
      let reg = /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/;
      if (!reg.test(that.form.primary_price)) {
        that.form.primary_price = "";
      }
    },
    // 验证输入
    changeCostPrice() {
      const that = this;
      let reg = /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/;
      if (!reg.test(that.form.cost_price)) {
        that.form.cost_price = "";
      }
    },
    // 验证输入
    changeNum() {
      const that = this;
      let reg = /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/;
      if (!reg.test(that.form.num)) {
        that.form.num = "";
      }
    },
    // 验证输入
    changeRate() {
      const that = this;
      let reg = /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/;
      if (!reg.test(that.form.rate)) {
        that.form.rate = "";
      }
    },

    // 生产日期
    onChangeProductionDate(data, string) {
      const that = this;
      that.form.production_date = string;
    },
	// 有效日期
	onChangeExpireDate(data, string) {
	  const that = this;
	  that.form.expire_date = string;
	},
	// 秒杀开始日期
	onChangeSeckillDate(data, string) {
	  const that = this;
	  that.form.astime = string;
	},
	// 秒杀结束日期
	onChangeSeckillEnd(data, string) {
	  const that = this;
	  that.form.aetime = string;
	},
   
    // 获取经营范围
    async GetTBusinessList() {
      const that = this;
      let res = await GetConfigList({ type: "business_scope" });
      if (res.data.code == 1) {
        let data = res.data.data;
        that.natureBusiness = data;
      } else {
        showError(res.data.msg);
      }
    },
    //过期日期
    onChange1(date, dateString) {
      console.log(date, dateString);
    },

    // 获取分类
    async GetCateList() {
      const that = this;
      let res = await GetProductCate({type:4});
      if (res.data.code == 1) {
        let data = res.data.data;
        that.cateList = data;
      } else {
        showError(res.data.msg);
      }
    },
    // 选择分类
    onChangeCate(value) {
      const that = this;
      that.form.cateId = value;
      console.log(value, this.form.cateId);
    },

    // 品牌搜索
    handleSearch(value) {
      const that = this;
      let params = {
        keyword: value,
        page: 1,
        pagesize: 10,
        type:2
      };
      GetProductBrandList(params).then((res) => {
        if (res.data.code == 1) {
          let data = res.data.data;
          that.ProductBrand = data.list;
        } else {
          showError(res.data.msg);
        }
      });
    },

    // 提交申请按钮
    async submitPush() {
      const that = this;
      const user = Vue.ls.get(USER_DATA);
      that.$refs["ruleForm"].validate(async (valid) => {
        console.log(valid);
        if (valid) {

          let form = that.form;
          let skuList = []
          if(form.spec_type == 1){ //单规格
            skuList = [
              {
                sale_price: form.sale_price,
                primary_price: form.primary_price,
                cost_price: form.cost_price,
                // rate_price:form.rate_price,
                num: form.num,
                settle_price:0,
                id:that.goodsId?form.sku_list[0].id:0
              },
            ];
          }else{ //多规格
          
            let data = that.skuTableData;
            if (!that.skuData.length) {
              //未添加规格项
              showError('请完善多规格项');
              return;
            } else if (that.skuData.length && !data.length) {
              //已添加规格项未处理规格组数据
              showError('请编辑规格属性');
              return;
            }
            for (let i = 0; i < data.length; i++) {
              if (
                data[i][data[i].length - 1].value == '' ||
                data[i][data[i].length - 2].value == '' ||
                data[i][data[i].length - 3].value == '' ||
                data[i][data[i].length - 4].value == ''
              ) {
                showError('请完善规格值');
                return;
              }
            }

            console.log(that.skuTableData);
            that.skuTableData.map(item=>{
              let obj = {}
              console.log(item);
              obj.cost_price = item[item.length-1].value
              obj.primary_price = item[item.length-2].value
              obj.sale_price = item[item.length-3].value
              obj.num = item[item.length-4].value
              obj.image = item[item.length-5].path
              obj.settle_price = 0
              let specTit = []
              for(let i = 0; i < item.length - 5; i++){
                console.log(i);
                specTit.push(item[i].key + ':' + item[i].value)
              }
              console.log(specTit);
              obj.product_spec = specTit.join(',')
              obj.id = item[0].id?item[0].id:0
              skuList.push(obj)
            })
            console.log(skuList);
          }

          let logo = []; //logo
          that.logo.map((item) => {
            item.url ? logo.push(item.url) : logo.push(item);
          });

          let image = []; //商品图片
          that.image.map((item) => {
            item.url ? image.push(item.url) : image.push(item);
          });

          let video = []; //商品视频
          that.video.map((item) => {
            item.url ? video.push(item.url) : video.push(item);
          });

          if(!form.cateId || !form.cateId.length){
            showError('请选择分类！')
            return
          }

          let params = {
            store_id:user.identityId,

            cate_pid: form.cateId[0],
            cate_id: form.cateId[1]?form.cateId[1]:0,
            title: form.title,
            brand_id: form.brand_id,
            code: form.code,
            synopsis: form.synopsis,
            sell_point: form.sell_point,
            drug_type: form.drug_type,
            category: form.category.join(","),
            meter_spec: form.meter_spec?form.meter_spec:0,
            medium_pack_spec: form.medium_pack_spec,
            spec_unit: form.spec_unit,
            spec_volume: form.spec_volume,
            activity_type:form.activity_type,
            is_daily:form.is_daily,
            astime:Math.round(new Date(form.astime) / 1000),
            aetime:Math.round(new Date(form.aetime) / 1000),
            alimit:form.alimit,
            approval_no: form.approval_no,
            manufacturer: form.manufacturer,

            production_date: form.production_date,
            expire_date: form.expire_date,

            specs:JSON.stringify(that.skuData),
            lists:JSON.stringify(that.skuTableData),

            rate: form.rate,

            desc: form.desc,
            pack_list: form.pack_list,
            after_service: form.after_service,
            smart_tag: form.smart_tag,

            logo: logo.join(","),
            image: image.join(","),
            video: video.join(","),
            type:2,
            spec_type:form.spec_type,
            sku_list: JSON.stringify(skuList),
            sale_price:form.sale_price,
            primary_price:form.primary_price,
            cost_price:form.cost_price,

            commission_rate:form.commission_rate,

            region_id:form.region_id,
            city_id:form.city_id,
            
            buy_limit:form.buy_limit,

            delivery_type: form.delivery_type,

            tag:form.tag
          };
          if (that.goodsId) {
            //编辑
            params.id = that.goodsId;
            let res = await yxnShopGoodsEdit(params);
            if (res.data.code == 1) {
              showSuccess("保存成功");
              that.$router.back(1);
              that.$refs.ruleForm.resetFields();
            } else {
              showError(res.data.msg);
            }
          } else {
            //新增
            let res = await yxnShopGoodsAdd(params);
            if (res.data.code == 1) {
              showSuccess("添加成功");
              that.$router.back(1);
              that.$refs.ruleForm.resetFields();
            } else {
              showError(res.data.msg);
            }
          }
        } else {
          showError("表单数据未完善！");
        }
      });
    },


    // 添加规格项
    addSkuItem(){
      const that = this;
      if(that.skuItem==''){
        showError('请输入规格项')
        return
      }
      if(that.skuData.findIndex(items=>items.skuItem == that.skuItem) != -1){
        showError('请勿重复添加规格项')
        return
      }
      let skuObj = {
        skuItem:'',
        skuChild:'',
        child:[], 
        new:that.skuTableData.length?true:false,
        sort:that.skuData.length
      }; //skuItem-添加的规格项，skuChild-双向绑定的输入添加规格值的input值，child-添加的规格值
      skuObj.skuItem = that.skuItem
      that.skuData.push(skuObj)
      that.skuItem = ''
    },
    // 添加规格值
    addSkuChild(item,index){
      const that = this;
      if(item.skuChild==''){
        showError('请输入规格值')
        return
      }
      if(that.skuData[index].child.findIndex(items=>items.skuChild == item.skuChild) != -1){
        showError('请勿重复添加规格值')
        return
      }
      that.skuData[index].child.push({
        skuChild:item.skuChild,
        new:that.skuTableData.length?true:false,
      });
      that.skuData[index].skuChild = ''
    },
    // 删除规格项
    delSkuItem(index){
      const that = this;
      console.log(that.skuData);
      const title = that.skuData[index].skuItem;
		  const tempSkuData = JSON.parse(JSON.stringify(that.skuData)); //删之前先保存一份用于后面判断
      that.skuData.splice(index,1);
      //删除完让sort重新获取值  不然后面添加规格排序会乱
      that.skuData.forEach((item, index) => {
        item.sort = index;
      });
      if (!that.skuTableData.length) {
        return false;
      }
      // 如果当前删除的规格里面没有值就不用在this.skuTableData中删除数据
      if (!tempSkuData[index].child.length) return false;
      // 如果删除的是最后一个规格，则清空所有数据
      if (that.skuTableData[0][1].type != "规格") {
        that.skuTableData = [];
        that.innerColumns = [];
        return false;
      }
      // 删除表中整列的数据
      that.deleteRowData(title);
      // 递归去重
      for (let i = 0; i < that.skuTableData.length; i++) {
        for (let j = i + 1; j < that.skuTableData.length; j++) {
          that.recursionJudgeValue(i, j, 0, true);
          if (that.delectFlag) {
            that.skuTableData.splice(j, 1);
            j--;
          }
        }
      }
      // 重新生成表头
      that.creatHeader();
    },
    
    // 删除规格值
    delSkuChild(index,indexs){
      const that = this;

      if (!that.skuTableData.length) {
        that.skuData[index].child.splice(indexs,1)
        return false;
      }
      const length = that.skuData[index].child.length;
      const value = that.skuData[index].child[indexs].skuChild;
      const title = that.skuData[index].skuItem;
      that.skuData[index].child.splice(indexs, 1);
      if (length > 1) {
        // 如果有多个值时就删除this.skuTableData中所有带有这个值的那一行
        content: for (let i = 0; i < that.skuTableData.length; i++) {
          value: for (let j = 0; j < that.skuTableData[i].length; j++) {
            if (that.skuTableData[i][j].value == value) {
              that.skuTableData.splice(i, 1);
              i--;
              break value;
            }
          }
        }
      }
      else {
        // 如果只有一个值 那么就把值从所有数据中删除 就是删除列
        that.skuData[index].new = true; //删除掉这个值 那么这个规格没有值了  就等同于是新添加的
        that.deleteRowData(title);
        if (
          that.skuTableData.length === 1 &&
          that.skuTableData[0][0].type != "规格"
        ) {
          // 如果删除的是最后的规格和最后一个值就清空所有数据
          that.skuTableData = [];
          that.innerColumns = [];
          return false;
        }
        // 重新生成表头
        that.creatHeader();
      }
    },

    // 递归去重
    recursionJudgeValue(i, j, count, flag) {
      const that = this;
      console.log(that.skuTableData);
      let tempFlag =
        that.skuTableData[i][count].value == that.skuTableData[j][count].value;
      let tempCount = count;
      const flag2 = flag && tempFlag;
      if (tempCount < that.skuData.length) {
        tempCount++;
        that.recursionJudgeValue(i, j, tempCount, flag2);
      } else {
        that.delectFlag = flag2;
      }
    },
    // 删除表中一列的数据
    deleteRowData(title) {
      const that = this;
      for (let i = 0; i < that.skuTableData.length; i++) {
        value: for (let j = 0; j < that.skuTableData[i].length; j++) {
          if (that.skuTableData[i][j].key == title) {
            that.skuTableData[i].splice(j, 1);
            break value;
          }
        }
      }
      console.log(that.skuTableData);
    },

    // 刷新生成表格数据按钮
    creatSkuTable(){
      const that = this;
      if (!that.skuData.length) {
        showError('请添加规格项')
        return
      } else {
        for (let i = 0; i < that.skuData.length; i++) {
          if (!that.skuData[i].child.length) {
            showError('请完善规格值')
            return
          }
        }
      }
      that.creatHeader();
      that.handleData()
    },
    // 生成表格表头
    creatHeader(){
      const that = this;
      console.log(that.skuData);
      let headerArr = [];
      that.skuData.map((item,index)=>{
        // 生成表头
          // dataIndex: 'sku' + index, 
        if(item.child.length){ //有规格值的才生成
          // headerArr.push({
          //   title: item.skuItem, 
          //   align: 'center',
          //   scopedSlots: { customRender: 'sku'+index }
          // })
          headerArr.push(item.skuItem)
        }
      })
      let fixedHeader = [
          // { title: '规格图', align: 'center', scopedSlots: { customRender: 'image' } },
          // { title: '库存', align: 'center', scopedSlots: { customRender: 'num' } },
          // { title: '售价', align: 'center', scopedSlots: { customRender: 'price' } },
          // { title: '原价', align: 'center', scopedSlots: { customRender: 'primcost' } },
          '规格图','库存','售价','原价','成本价'
      ];
      that.innerColumns = headerArr.concat(fixedHeader)
      console.log(that.innerColumns);
    },
    //刷新按钮处理表格数据
    handleData(){
      const listData = this.skuData.filter(item => item.child.length); //去掉没有值的规格
      // console.log(listData);
      if (this.skuTableData.length) {
        // 表格中数据不是第一次添加时
        let tempList = []; //用于存放新加的规格和值
        let tempContentList = this.skuTableData.length; //记录上一次数据的总长度
        listData.forEach((item, index) => {
          console.log(item);
          item.child.forEach((item2, index2) => {
            console.log(item2);
            if (item2.new) {
              // console.log('111111');
              // console.log(item2);
              //新添加的值
              let flag = false; // flag用于判断新值有没有添加进tempList
              let count = -1;
              // console.log(listData);
              flag = tempList.some((sitem, sindex) => {
                count++;
                return sitem.skuItem == item.skuItem;
              });
              // console.log(flag);
              if (flag) {
                //如果添加过则直接在里面的list追加
                tempList[count].child.push(item2);
              } else {
                //没添加过就添加一个新的对象
                tempList.push({
                  skuItem: item.skuItem,
                  child: [item2],
                  new: item.new,
                  sort: item.sort
                });
                // console.log(tempList);
              }
            }
          });
        });
        console.log(tempList);
        tempList.forEach(item => {
          console.log(item);
          const list = [];
          // list代表所有新值的规格和其他规格匹配的数据
          if (item.new && item.child.length == 1) {
            // 如果新加的规格的值只有一个，那么直接在每一列加新值
            for (let i = 0; i < tempContentList; i++) {
              this.skuTableData[i].splice(item.sort, 0, {
                type: "规格",
                value: item.child[0].skuChild,
                sort: item.sort,
                key: item.skuItem
              });
            }
          } else {
            // 如果新加的规格的值大于一个，那么先在每一列插入新值
            // 然后再拿其他值互相匹配
            if (item.new && item.child.length > 1) {
              for (let i = 0; i < tempContentList; i++) {
                this.skuTableData[i].splice(item.sort, 0, {
                  type: "规格",
                  value: item.child[0].skuChild,
                  sort: item.sort,
                  key: item.skuItem
                });
              }
              // 第一个值已经加进去，所以要删掉
              item.child.splice(0, 1);
            }
            // 先把新加的值加进去
            // console.log(item);
            // console.log(list);
            list.push(item);
            // console.log(list);
            listData.forEach(listItem => {
              console.log(listItem);
              listItem.child.forEach(listItem2 => {
                item.child.forEach(item2 => {
                  if (listItem2.skuChild == item2.skuChild) {
                    // 上面的新值已经加进去所以要在原来的listData中做标记
                    // 避免下面出现重复的组合
                    listItem2.disabled = true;
                  }
                });
              });
            });
            listData.forEach(listItem => {
              if (listItem.skuItem !== item.skuItem) {
                // 深拷贝避免影响原来的数据
                let tempListItem = JSON.parse(JSON.stringify(listItem));
                for (let count = 0; count < tempListItem.child.length; count++) {
                  if (tempListItem.child[count].disabled) {
                    //已经加过的值删掉
                    tempListItem.child.splice(count, 1);
                    count--;
                  }
                }
                list.push(tempListItem); // 加进list组合成新的数据
              }
            });
            list.sort((n1, n2) => n1.sort - n2.sort); //排序 避免新加的表中数据和表头对应不上
            // console.log(list);
            this.transformData(list);
          }
        });
        // 生成后把所有的值初始化 用于下次生成判断新值
        this.skuData.forEach(item => {
          item.new = false;
          item.child.forEach(item2 => {
            item2.new = false;
            item2.disabled = false;
          });
        });
        return false;
      }
      // console.log(listData);
      this.transformData(listData);
    },
    // 数据改造
    transformData(list){
      const that = this;
      console.log(that.skuData);
      let skuArr = []
      list.map(item=>{
        // 重组规格数据
        let arr = [];
        item.child.map(items=>{
          let obj = {
            type:'规格',
            key:item.skuItem,
            value:items.skuChild,
            sort:item.sort
          }
          arr.push(obj)
        })
        skuArr.push(arr)
      })
      // 生成新数据
      let skuCreatData = that.cartesianProductOf(...skuArr)
      skuCreatData.forEach(item=>{
        item.push({
          type: "规格图",
          path: "",
        });
        item.push({
          type: "库存",
          value: "",
        });
        item.push({
          type: "售价",
          value: "",
        });
        item.push({
          type: "原价",
          value: "",
        });
        item.push({
          type: "成本价",
          value: "",
        });
      })
      console.log(skuCreatData)
      //与原来的数据合并
      that.skuTableData.push(...skuCreatData);
    },
     formatData(params) {
    	//将时间戳（十三位时间搓，也就是带毫秒的时间搓）转换成时间格式
    	// d.cTime = 1539083829787
    	let date = new Date(params * 1000);
    	let year = date.getFullYear();
    	let month = date.getMonth() + 1;
    	let day = date.getDate();
    	let hour = date.getHours();
    	let minute = date.getMinutes();
    	let second = date.getSeconds();
    	month = month < 10 ? "0" + month : month;
    	day = day < 10 ? "0" + day : day;
    	date = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
    	return date;
    },
    // 笛卡尔积
    cartesianProductOf() {
      return Array.prototype.reduce.call(
        arguments,
        function(a, b) {
          var ret = [];
          a.forEach(function(a) {
            b.forEach(function(b) {
              ret.push(a.concat(b));
              // ret.push([...a, ...b]);
            });
          });
          return ret;
        },
        [
          []
        ]
      );
    },
    // 上传规格图片
		async handerFiles(event, index, index1) {
      const that = this;
			let file = event.target.files[0];
			let isLtSize = file.size / 1024 / 1024 < 10;
			// console.log(isLtSize);
			if (!isLtSize) {
				showError("上传文件不能超过 10MB!");
				return;
			}
			let form = new FormData();
			// console.log(event);
			// console.log(index);
      console.log(file,'file');
			form.append("file", file);
      form.get('file')
      console.log(form);
      // let res = await request.post('root/base/uploadfile',form)
      axios({
        method:'post',
        url:`${env.baseURL}root/base/uploadfile`,
        data:form
      }).then(res=>{
        console.log(res);
        if (res.data.code == 1) {
          showSuccess('上传成功')
          let data = res.data.data;
          that.skuTableData[index][index1].path = data.url;
        }else{
          showError(res.msg)
        }
      })
			// this.skuTableData[index][index1].img_id = data.id;
		},

  },
};
</script>

<style scoped lang="less">
.editable-row-operations a {
  margin-right: 12px;
}

.Main {
  border-radius: 10px;
  overflow: hidden;
  background: #fff;

  .MainTitle {
    font-size: 24px;
    color: #333;
    margin: 10px 20px;
    position: relative;
  }

  .MainTitle:before {
    content: "";
    width: 40px;
    height: 12px;
    background: linear-gradient(
      270deg,
      rgba(0, 158, 238, 0) 0%,
      rgba(0, 158, 238, 0.3) 100%
    );
    position: absolute;
    bottom: 2px;
    left: 0;
  }

  .MianContent {
    padding: 10px 20px 20px 20px;

    .MainTopAction {
      margin-bottom: 20px;
      display: flex;
      align-items: center;
      flex-wrap: wrap;

      .MainTopActionView {
        display: flex;
        align-items: center;
        flex-wrap: wrap;

        .MainTopActionOne {
          margin-right: 30px;

          span {
            margin-right: 20px;
          }
        }

        .MainTopActionTwo {
          span {
            margin-right: 20px;
          }
        }
      }

      .MainTopActionThree {
        display: flex;
        align-items: center;
        margin-left: 20px;
      }
    }
  }
}

.formBox {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 0.5rem;
}
.ant-form-item {
  display: flex;
  width: 100%;
}
.business {
  .ant-checkbox-group {
    padding: 20px;
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    grid-gap: 0.5rem;
    background: #f9f9f9;
  }
}

.skuBox {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 0.5rem;
}

.goodsAttribute {
  margin-top: 80px;
}

.qualiBox {
  margin-top: 80px;
}

.goodsImgBox {
  margin-top: 80px;
}
.btnBox {
  margin-top: 50px;
  display: flex;
  justify-content: center;
}
.skuTable{
  .skuText{
    background: #d6eef8;
    color: #3ab4e6;
    line-height: 25px;
    padding: 5px 10px;
    width: 80%;
  }
  .skuInputBox{
    border: 1px solid #ccc;
    margin: 20px 0;
    padding: 20px;
    .skuInput{
      
    }
    .skuChild{
      padding-left: 20px;
      .skuChildItem{
        border: 1px solid #ccc;
        line-height: 30px;
        border-radius: 5px;
        padding:0 10px;
        display: inline-block;
        margin: 0 5px;
      }
    }
  }
}

 table {
  width: 100%;
  border-collapse: collapse;
  .type {
      width: 8%;
  }
  thead {
      tr {
          width: 100%;
          // border-bottom: 1px solid #ccc;
          background: #F1F1F1;
          th {
              // width: 10%;
              height: 50px;
          }
      }
  }
  tbody {
      width: 100%;
      tr {
          height: 60px;
          border-bottom: 1px solid #F1F1F1;
      }
      td {
          // width: 10%;
          height: 25px;
          text-align: center;
      }
  }
  input {
      height: 30px;
      width: 80%;
      text-align: center;
  }
}
.spec_file {
	width: 30px;
	height: 30px;
	// background-color: red;
	border: 1px solid rgba(#101010,0.4);
	// border-right: 0;
	text-align: center;
	line-height: 30px;
	position: relative;
	margin: 0 auto;
	i{
		size: 12px;
		position: absolute;
		top: 6px;
		left: 6px;
		z-index: 1;
	}
	img {
		width: 20px;
		height: 20px;
		position: absolute;
		left: 4px;
		top: 4px;
	}
	input{
		width: 30px;
		height: 30px;
		position: absolute;
		z-index: 3;
		opacity: 0;
		left: 0;
		top: 0;
		cursor: pointer;
	}
}
</style>